const router = require('koa-router')(),
  { getAllUsers, checkUser, addUser } = require('../models/user'),
  jwt = require('jsonwebtoken'),
  log = console.log,
  { JWT_SECURITY_KEY, EXPIPES } = require('../config/security'),
  { cryptoPwd } = require('../utils/MD5')

router.prefix('/api/users');

//登录接口
router.post('/check', async (ctx, next) => {
  const { username, password } = ctx.request.body
  log(username, password)
  const resObj = checkUser(username, password)
  log(resObj)
  if (resObj.status) {
    ctx.body = { status: 1, message: resObj.message }
  } else {
    //生成token
    const token = jwt.sign({ id: resObj.id }, JWT_SECURITY_KEY, { expiresIn: EXPIPES })
    ctx.body = { id: resObj.id, status: 0, token: token, message: resObj.message }
  }
})

//注册接口
router.post('/add', async (ctx, next) => {
  const { username, password } = ctx.request.body
  console.log(username, password)
  const obj = addUser(username, password)
  if (obj.status) {
    ctx.body = { status: 1, message: obj.message }
  } else {
    ctx.body = { status: 0, message: obj.message } 
  }
})


module.exports = router;
